﻿using System;
namespace Sencha.Serialization.Serializers
{
	public sealed class DateTimeOffsetSerializer : TypeSerializer<DateTimeOffset>
	{
		public override DateTimeOffset Deserialize(IJsonReader reader)
		{
			if (reader.Token == JsonToken.DateTime)
				return new DateTimeOffset(reader.Value.AsDateTime, TimeSpan.Zero);

			var dateTimeOffsetStr = reader.ReadString(false);
			var value = DateTimeOffset.ParseExact(dateTimeOffsetStr, reader.Context.DateTimeFormats, reader.Context.Format, System.Globalization.DateTimeStyles.AssumeUniversal);
			return value;
		}
		public override void Serialize(IJsonWriter writer, DateTimeOffset value)
		{
			var dateTimeFormat = System.Linq.Enumerable.FirstOrDefault(writer.Context.DateTimeFormats);
			var valueStr = value.ToString(dateTimeFormat, writer.Context.Format);
			writer.Write(valueStr);
		}
	}
}
